<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>


    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            margin: 0 auto;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        *,
        *::before,
        *::after {
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
        }

        #app {
            width: 1200px;
            height: 800px;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            border: 1px orangered solid;
            padding: 10px;
            background-color: lightslategray;
        }

        .canvas_container {
            display: flex;
            /* width: 1000px;
            height: 800px; */
            background-color: lightgray;
            position: relative;
        }

        .char_area_container {
            display: flex;
            flex-direction: column;
            flex: 1;
            height: 100%;
            margin-left: 12px;
            background-color: lightsteelblue;
            padding: 0px 10px;
        }

        button {
            padding: 10px 15px;
            background-color: lightseagreen;
            border-radius: 4px;
            color: white;
            border: none;
            outline: none;
            cursor: pointer;
        }

        button.active {
            background-color: orangered;
            cursor: pointer;
        }

        [v-cloak] {
            display: none !important;
        }

        .canvas_mask {
            position: absolute;
            width: 100%;
            height: 100%;
            background-color: lightpink;
            opacity: 0.2;
        }

        .right_line {
            height: 50px;
            width: 100%;
            display: flex;
            justify-content: flex-start;
            align-items: center;
        }



        .area_line_each {
            line-height: 30px;
            display: flex;
            flex-direction: row;
            padding: 10px;
            background-color: lightslategray;
            margin-top: 1px;

        }

        .area_line_each>div {
            line-height: 30px;
        }

        .area_line_each_line {
            display: flex;
            flex-direction: row;
            width: 100%;
        }

        .item_right {
            flex-grow: 1;
            display: flex;
            align-items: center;
            margin-left: 10px;
            color: white;
        }

        .item_right_icon {
            width: 40px;
            display: flex;
            justify-content: center;
            cursor: pointer;
            color: white;
            font-size: 20px;
        }

        .item_copy_icon {
            width: 80px;
            display: flex;
            justify-content: center;
            cursor: pointer;
            color: lightsalmon;
            font-size: 12px;
        }

        .item_tool {
            width: 330px;
            display: flex;
            font-size: 16px;
        }

        .mr_5 {
            margin-right: 10px;
        }

        .mr_10 {
            margin-right: 10px;
        }

        .mt_10 {
            margin-top: 10px;
        }

        .my_input {
            outline: none;
            border: 1px lightcoral solid;
            padding: 3px 5px;
            width: 100%;
            font-size: 16px;
        }

        .search_input {
            width: 150px;
            height: 38px;
        }

        .result_input {
            width: 400px;
            height: 38px;
        }
    </style>

</head>

<body>

    <div id="app" v-cloak>
        <div class="canvas_container" id="canvas_container">
            <canvas id="canvas" width='413' height='500'></canvas>
            <!-- <div v-if="!selectMode" class="canvas_mask"></div> -->
        </div>
        <div class="char_area_container">
            <div class="right_line">




                <input class="my_input search_input mr_10" v-model="searchWord" placeholder="输入文字"
                    v-on:keyup.enter="getWordIdByName" />
                <input class="my_input result_input mr_10" v-model="searchResultWordId" placeholder="搜索出文字标识" />




                <!-- <button v-click="copyClick" class="">
                    结果
                </button> -->

            </div>
            <div class="area_line_container">
                <div v-for="react in reactList" class="area_line_each">
                    <div class="area_line_each_line">
                        <div class="item_tool">
                            <input class="my_input" v-model="react.WordId" />
                        </div>
                        <div class="item_right">{{react.FromX}}.{{react.FromY}}.{{react.ToX}}.{{react.ToY}}</div>
                        <div class="item_copy_icon" v-on:click="copyResultWordIdToHere(react)">复制标识到此</div>
                        <div class="item_right_icon" v-on:click="delItem(react)">x</div>
                    </div>

                </div>
                <!-- <div class="mt_10" v-if="reactList.length>0">注:测试请输入任意字母,用于模拟远程搜索</div> -->
            </div>

            <div class="mt_10">
                <button v-on:click="saveClick" class="mr_10">
                    全部保存
                </button>
            </div>

        </div>



    </div>

    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>

    <script src="https://cdn.bootcss.com/fabric.js/3.4.0/fabric.js"></script>


    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>

    <script>
        window.zoom = window.zoom ? window.zoom : 1;
        var drawWidth = 2; //笔触宽度
        var color = "#E34F51"; //画笔颜色
        var canvasObjectIndex = 0;
        var drawingObject = null; //当前绘制对象
        // var moveCount = 1; //绘制移动计数器
        // var doDrawing = false; // 绘制状态
        var mouseFrom = {};


        var mouseTo = {};

        //坐标转换
        function transformMouse(mouseX, mouseY) {
            return {
                x: mouseX / window.zoom,
                y: mouseY / window.zoom
            };
        }




        var vueApp = new Vue({
            el: '#app',
            data: {
                searchWord: '',
                searchResultWordId: '',
                visible: false,
                selectMode: false,
                delMode: false,
                reactList: [],
                options: [],
                value: [],
                list: [],
                loading: false,

                delIdsArr: [],
                _canvas: null,
                canvas_container_dom: null,

                moveCount: 1,
                doDrawing: false,
                directoryId: ''
            },
            mounted() {


                var map = this.getUrlParamsMap();
                // alert(map['DirectoryId']);
                this.directoryId = map['DirectoryId'] || map['directoryId'];

                var that = this;
                this.initCanvas(function () {
                    that.getBeiTieData();
                });



            },
            methods: {
                getWordIdByName() {
                    var that = this;
                    $.ajax({
                        type: "GET",
                        url: "http://localhost:98/api/Beitie/GetWordIdByName?wordName=" + this
                            .searchWord,
                        contentType: "application/json",
                        success: function (data) {


                            if (data.Data != null) {
                                that.searchResultWordId = data.Data.DirectoryID;
                            }
                            console.log(data), "========data==============";

                        },
                        error: function (data) {
                            console.log(data, "============error============");
                        }

                    });
                },
                getUrlParamsMap() {
                    var url = location.search; //获取url中"?"符后的字串
                    var theRequest = {};
                    if (url.indexOf("?") != -1) {
                        var urlArr = url.split("?");
                        var str = urlArr[1];
                        var strs = str.split("&");
                        for (var i = 0; i < strs.length; i++) {
                            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                        }
                    }
                    console.log(theRequest, "=========theRequest============");
                    return theRequest;
                },
                loadImg(url, callBack) {
                    var that = this;
                    var canvas = that._canvas;
                    fabric.Image.fromURL(url, function (oImg) {

                        oImg.width = oImg._element.width;
                        oImg.height = oImg._element.height;

                        canvas.setWidth(oImg.width * 0.7);
                        canvas.setHeight(oImg.height * 0.7);

                        that.canvas_container_dom.style.width = oImg.width * 0.7 + "px";
                        that.canvas_container_dom.style.height = oImg.height * 0.7 + "px";

                        oImg.preserveObjectStacking = true;

                        oImg.scaleX = 0.7;
                        oImg.scaleY = 0.7;

                        oImg.crossOrigin = 'anonymous';

                        oImg.selectable = false;

                        canvas.add(oImg);

                        callBack && callBack();

                    });
                },
                initCanvas(callBack) {

                    var that = this;

                    this._canvas = new fabric.Canvas('canvas'); //声明画布

                    var canvas = this._canvas;
                    canvas.selection = false;
                    canvas.skipTargetFind = true;
                    canvas.selectable = false;

                    canvas.defaultCursor = 'crosshair'; //默认光标改成十字
                    canvas.hoverCursor = 'crosshair'; //默认光标改成十字
                    // canvas.hoverCursor = 'pointer'; //悬浮光标改成手型

                    var url = "http://localhost:98/Images/beitie/寒食帖.png";
                    url = "http://223.68.159.69:1001/Images/beitie/Dazi/1.jpg"
                    // url="http://www.besteasylearn.com/pic/bt.jpg"

                    that.canvas_container_dom = document.getElementById("canvas_container");

                    that.loadImg(url, callBack);



                    // canvas.on("selection:created", function (e) {
                    //     console.log("=====selection:created=======" + new Date().getTime());

                    //     canvas.remove(e.target);
                    //     canvas.discardActiveObject(); //清楚选中框

                    //     var positionIndex = -1;
                    //     that.reactList.forEach((element, i) => {
                    //         if (element.id == e.target.index) {
                    //             positionIndex = i;

                    //             //如果不是为new开头就是未保存的
                    //             if (element.id.indexOf("new_") > -1) {

                    //             }
                    //             that.delIdsArr.push(element.id);
                    //             return;
                    //         }
                    //     });
                    //     console.log(positionIndex);
                    //     var arr = that.reactList;
                    //     arr.splice(positionIndex, 1);
                    //     console.log(arr, "=======arr=========");

                    //     that.reactList = arr;

                    //     // that._canvas.clear();
                    //     // var url = "http://localhost:98/Images/beitie/寒食帖.png";
                    //     // that.loadImg(url, callBack);
                    //     // that.drawingRender();

                    // });

                    //绑定画板事件
                    canvas.on("mouse:down", function (options) {
                        var xy = transformMouse(options.e.offsetX, options.e.offsetY);
                        mouseFrom.x = xy.x;
                        mouseFrom.y = xy.y;
                        that.doDrawing = true;
                        drawingObject = null;
                        // console.log("=====mouse:down=======" + new Date().getTime());
                    });

                    canvas.on('mouse:up', function (options) {

                        // 忽略很小的点击滑动
                        if (that.moveCount < 10) {

                            if (drawingObject) {
                                canvas.remove(drawingObject);
                            }

                            drawingObject = null;
                            that.moveCount = 1;
                            that.doDrawing = false;
                            return;
                        }

                        // console.log("=====mouse:up=======" + new Date().getTime());
                        var xy = transformMouse(options.e.offsetX, options.e.offsetY);
                        mouseTo.x = xy.x;
                        mouseTo.y = xy.y;
                        // drawing();



                        if (that.doDrawing) {
                            that.reactList.push({
                                CoordsId: drawingObject.index,
                                FromX: mouseFrom.x,
                                FromY: mouseFrom.y,
                                ToX: mouseTo.x,
                                ToY: mouseTo.y,

                                CoordsId: canvasObjectIndex, // 以new_开头为新增的
                                BeitieId: "21db9060-f6c7-4a6f-bdb6-528ee21753cc", //  676aa0a5-56c4-4f51-bccb-90b91aa034e6  21db9060-f6c7-4a6f-bdb6-528ee21753cc
                                WordId: "",

                                "CreateDate": "2019-09-10T00:18:58.677+08:00",
                                "CreateUserName": "王孟贵"
                            });
                        }
                        drawingObject = null;
                        that.moveCount = 1;
                        that.doDrawing = false;
                    })

                    canvas.on("mouse:move", function (options) {

                        if (that.moveCount % 2 && !that.doDrawing) {
                            //减少绘制频率
                            // console.log("=====mouse:return=======" + new Date().getTime());
                            return;

                        }
                        // console.log("=====mouse:move=======" + new Date().getTime());
                        that.moveCount = that.moveCount + 1;
                        var xy = transformMouse(options.e.offsetX, options.e.offsetY);
                        mouseTo.x = xy.x;
                        mouseTo.y = xy.y;
                        that.drawing();
                    });


                },
                //鼠标事件画的
                drawing() {
                    var that = this;
                    var canvas = that._canvas;

                    if (drawingObject) {
                        canvas.remove(drawingObject);
                    }

                    var canvasObject = null;
                    var path =
                        "M " +
                        mouseFrom.x +
                        " " +
                        mouseFrom.y +
                        " L " +
                        mouseTo.x +
                        " " +
                        mouseFrom.y +
                        " L " +
                        mouseTo.x +
                        " " +
                        mouseTo.y +
                        " L " +
                        mouseFrom.x +
                        " " +
                        mouseTo.y +
                        " L " +
                        mouseFrom.x +
                        " " +
                        mouseFrom.y +
                        " z";
                    var left = mouseFrom.x,
                        top = mouseFrom.y;
                    console.log(path, "========path=========");
                    canvasObject = new fabric.Path(path, {
                        left: left,
                        top: top,
                        stroke: color,
                        strokeWidth: drawWidth,
                        fill: "rgba(255, 255, 255, 0)"
                    });
                    if (canvasObject) {
                        canvas.add(canvasObject);
                        drawingObject = canvasObject;

                        var newGuid = "new_" + new Date().getTime();
                        canvasObject.index = newGuid;
                        canvasObjectIndex = newGuid;
                        console.log(canvasObject.index);

                    }
                },
                drawingRender: function (arr) {

                    var canvas = this._canvas;
                    for (var i = 0; i < arr.length; i++) {
                        var item = arr[i];

                        var path =
                            "M " +
                            item.FromX +
                            " " +
                            item.FromY +
                            " L " +
                            item.ToX +
                            " " +
                            item.FromY +
                            " L " +
                            item.ToX +
                            " " +
                            item.ToY +
                            " L " +
                            item.FromX +
                            " " +
                            item.ToY +
                            " L " +
                            item.FromX +
                            " " +
                            item.FromY +
                            " z";
                        var left = item.FromX,
                            top = item.FromY;
                        console.log(path, "========path=========");
                        canvasObject = new fabric.Path(path, {
                            left: left,
                            top: top,
                            stroke: color,
                            strokeWidth: drawWidth,
                            fill: "rgba(255, 255, 255, 0)"
                        });
                        if (canvasObject) {
                            canvas.add(canvasObject);
                            var newGuid = item.CoordsId
                            canvasObject.index = newGuid;
                            canvasObjectIndex = newGuid;
                            console.log(canvasObject.index);
                            drawingObject = canvasObject;
                        }
                    }
                },
                getBeiTieData() {

                    var that = this;

                    //模拟有数据

                    // this.reactList.push({
                    //     "CoordsId": "cd2ca10d-ad20-4086-9f60-2edf432a3d54",
                    //     "BeitieId": "676aa0a5-56c4-4f51-bccb-90b91aa034e6",
                    //     "WordId": "00feae25-b3de-4f3f-ac5a-3c5b1f4ab038",
                    //     "FromX": 137,
                    //     "FromY": 128,
                    //     "ToX": 265,
                    //     "ToY": 316,
                    //     "CreateDate": "2019-09-10T00:18:58.677+08:00",
                    //     "CreateUserName": "王孟贵"
                    // });

                    // that.drawingRender(this.reactList);
                    // drawingObject = null;
                    // return false;

                    $.ajax({
                        type: "GET",
                        url: "http://localhost:98/api/Beitie/GetBeitieCoordsListById?keyword=" + this
                            .directoryId,
                        contentType: "application/json",
                        success: function (data) {

                            that.reactList = data.Data;

                            that.drawingRender(data.Data);
                            drawingObject = null;
                            console.log(data, "============data============");
                        },
                        error: function (data) {
                            console.log(data, "============error============");
                        }

                    });
                },
                copyClick() {},
                saveClick() {
                    var that = this;

                    this.reactList.forEach((item, index) => {
                        if (item.CoordsId.indexOf('new_') > -1) {
                            item.CoordsId = '';
                        }
                    })

                    $.ajax({
                        type: "POST",
                        url: "http://localhost:98/api/Beitie/SaveBeitieWordCoords",
                        contentType: "application/json",
                        data: JSON.stringify(this.reactList),
                        success: function (data) {
                            //弹框关闭或刷新
                            console.log(data, "============data============");
                            if (data.Code == 2) {
                                alert("保存成功;");
                                //国保存成功后新增的id并没返回 如果再保存 扔会新增
                                // 方案一: 关闭弹框,再进就是重新拉了
                                // 方案二: 重新加载页面
                                // 方案二: 重新拉取并重给
                                // 选 第三种
                                that.getBeiTieData();
                            }
                        },
                        error: function (data) {
                            console.log(data, "============error============");
                        }

                    });
                },
                changeSelectMode() {
                    this.doDrawing = !this.doDrawing;
                },
                remoteMethod(query) {

                    if (query !== '') {
                        this.loading = true;
                        setTimeout(() => {
                            this.loading = false;
                            this.options = this.list.filter(item => {
                                return item.label.toLowerCase()
                                    .indexOf(query.toLowerCase()) > -1;
                            });
                        }, 200);
                    } else {
                        this.options = [];
                    }
                },
                copyResultWordIdToHere(item) {
                    item.WordId = this.searchResultWordId;
                    this.searchWord = '';
                    this.searchResultWordId = "";
                },
                delItem: function (item) {
                    // alert(item.CoordsId);

                    var that=this;

                    //this.reactList数据驱动 全清再渲染
                    var arr = this.reactList;
                    for (var i = 0; i < arr.length; i++) {
                        if (arr[i].CoordsId == item.CoordsId) {
                            console.log(arr[i].index, "=======找到删除的======")

                            //如果不是为new开头就是未保存的
                            if (arr[i].CoordsId.indexOf("new_") == -1) {
                                that.delIdsArr.push(arr[i].CoordsId);
                            }
                            this.reactList = arr.splice(i, 1);
                            break;
                        }
                    }


                    // that.delIdsArr 可以用于收集一起 保存时删除
                    // 或每次点删除时异步删除 回调后再 that._canvas.clear() 并重画



                    $.ajax({
                        type: "GET",
                        url: "http://localhost:98/api/Beitie/DeleteBeitiePos",
                        contentType: "application/json",
                        data: {
                            keyValue: item.CoordsId
                        },
                        success: function (data) {
                            //弹框关闭或刷新
                            console.log(data, "============data============");
                            if (data.Code == 2) {
                                // alert("保存成功;");
                                that.getBeiTieData();
                            }
                        },
                        error: function (data) {
                            console.log(data, "============error============");
                        }

                    });


                    // that._canvas.clear();
                    // this.reactList = arr;
                    // console.log(this.reactList, "=========reactList===========");

                    // var url = "http://localhost:98/Images/beitie/寒食帖.png";
                    // url = "http://223.68.159.69:1001/Images/beitie/Dazi/1.jpg"
                    // that.loadImg(url, function () {
                    //     that.drawingRender(that.reactList);
                    // });




                    //1: 获得画布上的所有对象：
                    //var arr = this._canvas.getObjects();
                    // for (var i = 0; i < arr.length; i++) {
                    //     if (arr[i].index == item.CoordsId) {
                    //         arr.splice(i, 1);
                    //         break;
                    //     }
                    // }



                }
            }
        })
    </script>

</body>

</html>